package com.raptor.redis.spring;

import com.raptor.redis.config.RedisConfigBean;
import com.raptor.redis.config.RedisConfig;
import com.raptor.redis.exception.RedisException;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.Arrays;
import java.util.List;

/**
 * @program: raptor-boot
 * @description: Redis实例初始化
 */
@Order(1)
@ComponentScan("com.shihang.core.redis.*")
public class RedisApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(RedisApplicationContextInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        Object[] objects = propertySources.stream().toArray();

        if (objects.length == 0) {
            throw new RedisException("读取配置文件失败!");
        }

        Arrays.asList(objects).forEach(obj -> {
            if ((obj instanceof PropertiesPropertySource)) {
                PropertiesPropertySource targetPropertySource = (PropertiesPropertySource) obj;
                RedisConfig config = new RedisConfig(targetPropertySource);
                List<RedisConfigBean> beans = config.GetRedisConfig();
                beans.forEach(b -> {
                    // 多实例redis注册bean
                    RedisRegisterBean registerBean = new RedisRegisterBean(b, configurableApplicationContext);
                    registerBean.RegisterRedisBean();
                    logger.info(b.instanceName + "初始化成功");
                });
            }
        });
    }
}
